﻿using Core.Framework.Model.Common;
using Core.Framework.Model.WebSockets;
using Core.Framework.Util;
using Core.IBusiness.ILoggerModule;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.WebSockets;

namespace Core.Service.TaskHandle
{
    public abstract class BaseMQMsgListener
    {

        /// <summary>
        /// 日志接口
        /// </summary>
        protected ILog iLog = BuildServiceProvider.GetService<ILog>();

        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="messageQueue"></param>
        public async void SendMessage(WebSocket client, string jsonData)
        {

            var clientInfo = WebSocketApplication.ClientsPool[client];

            lock (clientInfo)
            {
                clientInfo.TaskLength = clientInfo.TaskLength+1;
            }

            await WebSocketApplication.SendAsync(client, jsonData);

            MessageBackCall(clientInfo.Project?.CallUrl, jsonData);

            
        }

        /// <summary>
        /// 回调通知
        /// </summary>
        /// <returns></returns>
        public void MessageBackCall(string callUrl,string jsonData)
        {
            try
            {
                if (!string.IsNullOrWhiteSpace(callUrl) && callUrl.IndexOf("http") > -1)
                {
                    HttpClient httpClient = new HttpClient();
                    var postData = new StringContent(jsonData);
                    postData.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
                    httpClient.PostAsync(new Uri(callUrl), postData);
                }
            }
            catch
            {
            }
        }

        /// <summary>
        /// 构造发送参数
        /// </summary>
        /// <returns></returns>
        public virtual string StructureParameter(MessageQueue messageQueue)
        {
            return new
            {
                Token = messageQueue.Message.Token,
                message = messageQueue.Message.Content,
                messageParameter = messageQueue.Message.Parameter,

                userKey = messageQueue.ClientInfo.User.Key,
                MessageKey = messageQueue.Message.Channel,
                userParameter = messageQueue.ClientInfo.User.Parameter,
                sendDateTime = messageQueue.Message.SendDateTime,
                template = messageQueue.Template.ToLower(),

                messageType = messageQueue.Message.MessageType.ToString(),
                type = "current"

            }.TryToJson();
        }




        /// <summary>
        /// 添加消费消息失败日志
        /// </summary>
        /// <param name="messageQueue"></param>
        public void AddLogConsumFail(MessageQueue messageQueue)
        {
            iLog.Queue<BaseMQMsgListener>(new
            {
                Client = CoreStartupHelper.GetConfigValue("Service:Title"),
                Message = "暂无可用客户端"
            }.TryToJson(), "consum_fail",
                            messageQueue.ClientInfo.Project.ProjectToken,
                            messageQueue.Message.Token);
        }

        /// <summary>
        /// 添加消费消息日志
        /// </summary>
        /// <param name="messageQueue"></param>
        /// <param name="json"></param>
        public void AddLogConsum(MessageQueue messageQueue, string json)
        {
            iLog.Queue<BaseMQMsgListener>(new
            {
                Client = CoreStartupHelper.GetConfigValue("Service:Title"),
                TaskUserKey = messageQueue.ClientInfo.User.Key,
                SendMessage = json
            }.TryToJson(), "consum",
                            messageQueue.ClientInfo.Project.ProjectToken,
                            messageQueue.Message.Token);
        }

        /// <summary>
        /// 添加消费消息错误日志
        /// </summary>
        /// <param name="messageQueue"></param>
        /// <param name="json"></param>
        public void AddLogConsumError(MessageQueue messageQueue, string message)
        {

            iLog.Queue<BaseMQMsgListener>(new
            {
                Client = CoreStartupHelper.GetConfigValue("Service:Title"),
                TaskUserKey = messageQueue.ClientInfo.User.Key,
                Message = message
            }.TryToJson(), "consum_error",
                            messageQueue.ClientInfo.Project.ProjectToken,
                            messageQueue.Message.Token);
        }

        /// <summary>
        /// 添加处理消息错误日志
        /// </summary>
        /// <param name="messageQueue"></param>
        /// <param name="json"></param>
        public void AddLogWebSocketError(MessageQueue messageQueue, string message)
        {
            iLog.Queue<BaseMQMsgListener>(new
            {
                Client = CoreStartupHelper.GetConfigValue("Service:Title"),
                Message = message
            }.TryToJson(), "error",
                    messageQueue.ClientInfo.Project.ProjectToken,
                    messageQueue.Message.Token);
        }




        /// <summary>
        /// 根据ClientId 获取Ws会话
        /// </summary>
        /// <returns></returns>
        public List<WebSocket> GetWebSocketListByClientIds(string projectToken,List<string> cids)
        {
            List<WebSocket> wss = new List<WebSocket>();

            foreach (var item in cids)
            {

                var hashName = $"{projectToken}_{item}";

                // 检查是否存在当前会话
                if (WebSocketApplication.ClientIdsPool.ContainsKey(hashName))
                {
                    // 获取当前会话
                    var ws = WebSocketApplication.ClientIdsPool[hashName];

                    // 检查会话状态
                    if (ws.State == WebSocketState.Open)
                    {
                        wss.Add(ws);
                    }
                    else
                    {
                        // 不在线则移除
                        WebSocketApplication.ClientLoginOut(ws);
                    }
                }

            }

            return wss;

        }
    }
}
